package com.io.server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by 41579 on 2016/12/20.
 */
public class IOServer {
    private static Map<String, Socket> socketMap = new HashMap<String, Socket>();

    public static void main(String[] args) throws Exception {
        ServerSocket ss = new ServerSocket(1000);
        System.out.println(ss.getReceiveBufferSize());
        while (true) {
            Socket s = ss.accept();
            System.out.println("和客户端建立连接。。。。。");
            Thread t = new Thread(new myThread(s));
            System.out.println(t.getName());
            t.start();
            System.out.println("客户端线程建立结束，等待下一个连接。。。。。");
        }
    }

    static class myThread implements Runnable {
        Socket s;

        public myThread(Socket s) {
            this.s = s;
        }

        public void run() {
            try {
                InputStream is = s.getInputStream();
                byte[] bytes = new byte[3];
                while (is.read(bytes) > 0) {            //所谓的阻塞是发生在这里，NIO只能解决这个问题
                    System.out.println("客户端发来请求：" + new String(bytes));
                    OutputStream os = s.getOutputStream();
                    os.write((Thread.currentThread().getName()+"\n").getBytes());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
